import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
const {PosPrinter} = require("electron-pos-printer");
const  printPort = (event,goodData,title,totalNum,totalPrice,orderNumber,payType,userId,userMoney,dateStr,userPhoneStr) =>{
  console.log(event);
  const options:any = {
      preview: false,
      margin: '0 0 0 0',
      copies: 1,
      silent:true,
      timeOutPerLine: 1000,
      pageSize: '58mm' // page size
  } 
  let goodList = JSON.parse(goodData);
  if(payType == 1){
    payType = '微信';
  }else if(payType == 2){
    payType = '支付宝';
  }else if(payType == -1){
    payType = '现金';
  }else{
    payType = '余额支付';
  }
  
  type GoodDetail = {
    title: string;
    num: number;
    vipPrice: number;
    price: number;
    thisAllPrice: number;
  };

  let goodArr: Array<Array<GoodDetail>> = [];
  for (const item in goodList) {
      let tem: GoodDetail[]= [];
      tem.push(goodList[item]['title']);
      tem.push(goodList[item]['num'].toString());
      if(userId>0){
        tem.push(goodList[item]['vipPrice'].toString());
      }else{
        tem.push(goodList[item]['price'].toString());
      }
      tem.push(goodList[item]['thisAllPrice'].toString());
      goodArr.push(tem);
  }
  
  const printData = [
    {
      type: 'text', 
      value: '欢迎光临八臻八戒旗舰店',  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "14px"
      } 
    },
    {
      type: 'text', 
      value: title,  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "14px"
      } 
    },
    {
      type: 'text', 
      value: '=================================',  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "14px"
      } 
    },
    {
      type: 'table',
      // style the table
      style: {border: '2px solid #ddd'},
      // list of the columns to be rendered in the table header
      tableHeader: ['名称', '数量' , '单价', '总价'],
      // multi dimensional array depicting the rows and columns of the table body
      tableBody: goodArr,
      // list of columns to be rendered in the table footer
      tableFooter: ['总数',totalNum,'总价',totalPrice],
      // custom style for the table header
      tableHeaderStyle: { backgroundColor: '#000', color: '#000',fontWeight: "1000", fontSize: "14px"},
      // custom style for the table body
      tableBodyStyle: {'border': '2px solid #ddd',color: '#000',fontWeight: "1000", fontSize: "14px"},
      // custom style for the table footer
      tableFooterStyle: {backgroundColor: '#000', color: '#000',fontWeight: "1000", fontSize: "14px"},
  },
  {
      type: 'text', 
      value: '支付方式:'+payType+',余额:'+userMoney,  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "14px"
      } 
    },
    {
      type: 'text', 
      value: '订单:'+orderNumber,  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "12px"
      } 
    },
    {
      type: 'text', 
      value: '时间:'+dateStr,  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "12px"
      } 
    },
    {
      type: 'text', 
      value: '手机号:'+userPhoneStr,  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "12px"
      } 
    },
    {
      type: 'text', 
      value: '请当面点清所购商品',  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "14px"
      } 
    },
    {
      type: 'text', 
      value: '谢谢惠顾',  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "14px"
      } 
    },
    {
      type: 'text', 
      value: '更多优惠请关注八臻八戒小程序',  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "14px"
      } 
    },
    {
      type: 'text', 
      value: '=================================',  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "14px"
      } 
    },
    {
      type: 'text', 
      value: '=================================',  
      style: {
        fontWeight: "500", textAlign: 'center', fontSize: "14px"
      } 
    }
    // ...更多打印内容
  ];
  PosPrinter.print(printData, options)
  .then(console.log)
  .catch((error) => {
      console.error(error);
    });
}
app.commandLine.appendSwitch('disable-web-security');
function createWindow():void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    frame: false,
    fullscreen: true,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      nodeIntegration: true,
      contextIsolation: false
    }
  })
  
  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })
  //mainWindow.webContents.openDevTools();

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
  
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  const gotTheLock = app.requestSingleInstanceLock();
  if (!gotTheLock) {
    app.quit();
  }else {
    app.on('second-instance', () => {
      // 当运行第二个实例时，聚焦到第一个实例窗口
      const allWindows = BrowserWindow.getAllWindows();
      if (allWindows.length > 0) {
        const currentWindow = allWindows[0];
        if (currentWindow.isMinimized()) currentWindow.restore();
        currentWindow.focus();
      }
    });
  }
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })
  // 添加打开开发者工具的处理函数
  ipcMain.on('open-devtools', () => {
    const currentWindow = BrowserWindow.getFocusedWindow();
    if (currentWindow) {
      currentWindow.webContents.openDevTools();
    }
  })
  
  // 添加显示隐藏输入框的处理函数
  ipcMain.on('show-hidden-input', () => {
    const currentWindow = BrowserWindow.getFocusedWindow();
    if (currentWindow) {
      currentWindow.webContents.send('show-hidden-input-renderer');
    }
  })
  // IPC test
  ipcMain.on('print', (event,goodData,title,totalNum,totalPrice,orderNumber,payType,userId,userMoney,dateStr,userPhoneStr) => {
    printPort(event,goodData,title,totalNum,totalPrice,orderNumber,payType,userId,userMoney,dateStr,userPhoneStr);
  })
  ipcMain.on('logout', () => {
    app.quit();
  })
  ipcMain.on('miniwin', () => {
      const allWindows = BrowserWindow.getAllWindows();
      if (allWindows.length > 0) {
          const currentWindow = BrowserWindow.getFocusedWindow();
          if (currentWindow) {
              currentWindow.minimize();
          }
      }
  })
  createWindow()
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
 

})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
